# coding=utf-8
# author:xc
# datetime:2018/9/5 14:04

from flask import render_template, request, jsonify
from dbConnection.MysqlConn import Mysql
from . import admin
from app import upload_files, util
import time


@admin.route('/admin/version/list.html', methods=['POST', 'GET'])
@util.login_required
def admin_version_list():
    if request.method == 'GET':
        mysql = Mysql()
        sql = "select * from news_version "
        result = mysql.getAll(sql, None)
        mysql.dispose()
        data = {
            'data': result
        }
        return render_template('admin/setting/version_list.html', res=data)


@admin.route('/admin/version/stop', methods=['POST'])
@util.login_required
def admin_stop():
    apk_id = request.values.get('id')
    mysql = Mysql()
    sql = "update news_version set status=0 where id='%s'" % apk_id
    res = mysql.update(sql, None)
    mysql.dispose()
    code = util.CODE_EMPTY
    if res:
        code = util.CODE_SUCCESS
    data = {
        'code': code
    }
    return util.to_json(data)


@admin.route('/admin/version/start', methods=['POST'])
@util.login_required
def admin_start():
    apk_id = request.values.get('id')
    mysql = Mysql()
    sql = "update news_version set status=1 where id='%s'" % apk_id
    res = mysql.update(sql, None)
    mysql.dispose()
    code = util.CODE_EMPTY
    if res:
        code = util.CODE_SUCCESS
    data = {
        'code': code
    }
    return util.to_json(data)


@admin.route('/admin/version/add.html', methods=['POST', 'GET'])
@util.login_required
def admin_version_add():
    if request.method == 'GET':
        return render_template('admin/setting/version_add.html')
    else:
        version_code = request.values.get('version_code')
        version_name = request.values.get('version_name')
        apk_file = request.files['all_file']
        name = str(apk_file.filename.split('/')[-1:][0])
        cdn_path = 'news/' + str(int(time.time())) + name
        url = upload_files.upload_image(apk_file, cdn_path, name)
        url = url['url']
        mysql = Mysql()
        sql = "insert into news_version(version_code,version_num,url,addTime)VALUES ('%s','%s','%s',now())" % (
            version_code, version_name, url)
        res = mysql.insertOne(sql, None)
        mysql.dispose()
        status = 0
        if res:
            status = 1
        data = {
            'status': status
        }
        return jsonify(data)
